package com.github.hgkmail.hello.leetcode101.binarysearch;

public class LC81SearchInRotatedSortedArray2 {
    public boolean search(int[] nums, int target) {
        if (nums.length==0) {
            return false;
        }
        if (nums.length==1) {
            return nums[0] == target;
        }
        //二分，左闭右闭
        int l=0;
        int r=nums.length-1;
        int mid;
        while (l<=r) {
            mid=l+(r-l)/2;
            if (nums[mid]==target) {
                return true;
            }
            if (nums[mid]==nums[l]) { //无法判断有序性
                l++;
            } else if (nums[mid]==nums[r]) { //无法判断有序性
                r--;
            } else if (nums[mid]>nums[l]) { //左边有序
                if (target>=nums[l] && target<=nums[mid]) { //在里面
                    r=mid-1;
                } else { //不在里面，即在另一边
                    l=mid+1;
                }
            } else { //右边有序
                if (target>=nums[mid] && target<=nums[r]) { //在里面
                    l=mid+1;
                } else { //不在里面，即在另一边
                    r=mid-1;
                }
            }
        }

        return false;
    }

    public static void main(String[] args) {

    }
}
